/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jsf.util;

import java.beans.*;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Geymen
 */
public class SearchBean implements Serializable {
    
    public static final String PROP_SAMPLE_PROPERTY = "courseList";
    private List<Integer> courseList;
    private PropertyChangeSupport propertySupport;
    
    public SearchBean() {
        propertySupport = new PropertyChangeSupport(this);
    }
    
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("EducationXPU");

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
        
    public List<Integer> getSearchedCoursesForSearchKeyAndUserID(String searchKey, Integer userID) {
        try {
            EntityManager em;
            em = getEntityManager();
            em.getTransaction().begin();

            Connection connection = em.unwrap(java.sql.Connection.class); // unwraps the Connection class.
            CallableStatement cs;

            em.getTransaction().commit();

            cs = connection.prepareCall("{call GetSearchedCourses(?, ?)}");
            cs.setString(1, searchKey);
            cs.setInt(2, userID);
            ResultSet rs = cs.executeQuery();

            courseList = new ArrayList<Integer>();
            while (rs.next()) {
                String courseid = rs.getString("courseid");
                courseList.add(new Integer(Integer.parseInt(courseid)));
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(RecommendationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return courseList;
    }
    
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.addPropertyChangeListener(listener);
    }
    
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.removePropertyChangeListener(listener);
    }
}